/**
 * 荒岛生存游戏核心管理器
 * 负责游戏状态管理、资源计算、技能成长、结局判定
 */

class IslandGameManager {
  constructor() {
    // 初始化游戏状态
    this.initDefaultState()
  }

  /**
   * 初始化默认游戏状态
   */
  initDefaultState() {
    this.state = {
      // 基础属性
      hp: 100,
      hunger: 100,
      energy: 100,
      thirst: 100,
      sanity: 100,
      temperature: 37,
      
      // 游戏进度
      day: 1,
      currentLocation: 'beach',
      difficulty: 'normal',
      
      // 资源库存
      inventory: {
        berry: 0,
        fish: 0,
        meat: 0,
        wood: 0,
        stone: 0,
        vine: 0,
        water: 0,
        coconut: 0,
        axe: 0,
        spear: 0,
        fishing_rod: 0,
        medicine: 0,
        torch: 0,
        map_fragment: 0
      },
      
      // 高级物品
      advancedItems: {
        rope: 0,
        plank: 0,
        cooked_meat: 0,
        dried_fish: 0,
        iron_axe: 0,
        compass: 0
      },
      
      // 技能等级
      skills: {
        gathering: { level: 0, exp: 0 },
        hunting: { level: 0, exp: 0 },
        crafting: { level: 0, exp: 0 },
        survival: { level: 0, exp: 0 },
        exploration: { level: 0, exp: 0 }
      },
      
      // 建筑
      buildings: {
        shelter: false,
        campfire: false,
        water_collector: false,
        storage: false,
        workshop: false,
        boat: false,
        signal_tower: false
      },
      
      // 已探索区域
      exploredLocations: {
        beach: true,
        forest: false,
        mountain: false,
        cave: false,
        ruins: false,
        harbor: false
      },
      
      // NPC关系
      npcs: {
        mysterious_figure: { unlocked: false, mood: 50, friendship: 0 },
        robinson: { unlocked: false, mood: 50, friendship: 0 },
        parrot: { unlocked: false, mood: 80, friendship: 0 }
      },
      
      // 状态标记
      flags: {
        wildlife_tamed: false,
        mysterious_book_found: false,
        full_map_obtained: false,
        companion: null
      },
      
      // 已触发事件
      triggeredEvents: [],
      
      // 游戏结局
      ending: null,
      isGameOver: false
    }
  }

  /**
   * 开始新游戏
   */
  startNewGame(difficulty = 'normal') {
    this.initDefaultState()
    this.state.difficulty = difficulty
    this.applyDifficultyModifiers()
    this.saveState()
    return this.state
  }

  /**
   * 应用难度修正
   */
  applyDifficultyModifiers() {
    const modifiers = {
      easy: { consumption: 0.7, resourceBonus: 1.5, danger: 0.5 },
      normal: { consumption: 1.0, resourceBonus: 1.0, danger: 1.0 },
      hard: { consumption: 1.3, resourceBonus: 0.7, danger: 1.5 },
      nightmare: { consumption: 1.5, resourceBonus: 0.5, danger: 2.0 }
    }
    
    this.difficultyModifier = modifiers[this.state.difficulty]
  }

  /**
   * 每日结算
   */
  async advanceDay() {
    this.state.day++
    
    // 每日消耗
    this.dailyConsumption()
    
    // 检查建筑效果
    this.applyBuildingEffects()
    
    // 检查状态异常
    this.checkStatusEffects()
    
    // 检查结局条件
    const ending = this.checkEndings()
    if (ending) {
      return { gameOver: true, ending }
    }
    
    // 检查剧情事件
    const storyEvent = this.checkStoryEvents()
    if (storyEvent) {
      return { storyEvent }
    }
    
    // 随机事件
    const randomEvent = this.checkRandomEvents()
    if (randomEvent) {
      return { randomEvent }
    }
    
    this.saveState()
    return { day: this.state.day, state: this.state }
  }

  /**
   * 每日消耗
   */
  dailyConsumption() {
    const modifier = this.difficultyModifier.consumption
    
    // 基础消耗
    this.state.hunger = Math.max(0, this.state.hunger - 5 * modifier)
    this.state.thirst = Math.max(0, this.state.thirst - 10 * modifier)
    this.state.energy = Math.max(0, this.state.energy - 3 * modifier)
    
    // 生存技能减少消耗
    if (this.state.skills.survival.level >= 3) {
      this.state.hunger = Math.min(100, this.state.hunger + 2)
      this.state.thirst = Math.min(100, this.state.thirst + 3)
    }
    
    // 饥渴惩罚
    if (this.state.hunger <= 20) {
      this.state.hp = Math.max(0, this.state.hp - 5)
      this.state.sanity = Math.max(0, this.state.sanity - 3)
    }
    
    if (this.state.thirst <= 10) {
      this.state.hp = Math.max(0, this.state.hp - 8)
      this.state.sanity = Math.max(0, this.state.sanity - 5)
    }
    
    // 理智值恢复（如果有篝火）
    if (this.state.buildings.campfire) {
      this.state.sanity = Math.min(100, this.state.sanity + 5)
    }
  }

  /**
   * 应用建筑效果
   */
  applyBuildingEffects() {
    // 集水器每日产水
    if (this.state.buildings.water_collector) {
      this.state.inventory.water += 5
    }
  }

  /**
   * 检查状态效果
   */
  checkStatusEffects() {
    // 虚弱状态
    if (this.state.hp < 30 || this.state.hunger < 30 || this.state.energy < 30) {
      this.state.statusEffect = 'weak'
    } 
    // 濒死状态
    else if (this.state.hp < 20) {
      this.state.statusEffect = 'dying'
    }
    // 疯狂状态
    else if (this.state.sanity < 20) {
      this.state.statusEffect = 'mad'
    }
    // 健康状态
    else if (this.state.hp > 60 && this.state.hunger > 60 && this.state.energy > 60) {
      this.state.statusEffect = 'healthy'
    }
    else {
      this.state.statusEffect = 'normal'
    }
  }

  /**
   * 执行行动
   */
  async performAction(action, params = {}) {
    switch (action) {
      case 'gather':
        return this.gatherResources(params.location)
      case 'hunt':
        return this.hunt()
      case 'fish':
        return this.fish()
      case 'craft':
        return this.craftItem(params.item)
      case 'build':
        return this.buildStructure(params.building)
      case 'explore':
        return this.exploreLocation(params.location)
      case 'rest':
        return this.rest()
      case 'eat':
        return this.eat(params.food)
      case 'drink':
        return this.drink(params.water)
      default:
        return { success: false, message: '未知行动' }
    }
  }

  /**
   * 采集资源
   */
  gatherResources(location = null) {
    const currentLoc = location || this.state.currentLocation
    
    // 消耗精力
    if (this.state.energy < 10) {
      return { success: false, message: '精力不足，需要休息' }
    }
    
    this.state.energy -= 10
    
    // 根据位置获取资源
    const resources = this.getLocationResources(currentLoc)
    
    // 采集数量（受技能影响）
    const baseAmount = 2
    const skillBonus = this.state.skills.gathering.level >= 3 ? 1 : 0
    const toolBonus = this.state.inventory.axe > 0 ? 0.5 : 0
    const amount = Math.floor(baseAmount * (1 + skillBonus + toolBonus))
    
    // 随机选择一个资源
    const resource = resources[Math.floor(Math.random() * resources.length)]
    this.state.inventory[resource] = (this.state.inventory[resource] || 0) + amount
    
    // 增加经验
    this.addSkillExp('gathering', 10)
    
    this.saveState()
    return {
      success: true,
      message: `采集到 ${amount} 个 ${this.getResourceName(resource)}`,
      resource,
      amount
    }
  }

  /**
   * 狩猎
   */
  hunt() {
    if (!this.state.inventory.spear) {
      return { success: false, message: '需要矛才能狩猎' }
    }
    
    if (this.state.energy < 20) {
      return { success: false, message: '精力不足' }
    }
    
    this.state.energy -= 20
    
    // 成功率（受技能影响）
    const baseRate = 0.5
    const skillBonus = this.state.skills.hunting.level * 0.02
    const successRate = Math.min(0.9, baseRate + skillBonus)
    
    if (Math.random() < successRate) {
      const amount = this.state.skills.hunting.level >= 10 ? 5 : 3
      this.state.inventory.meat += amount
      this.addSkillExp('hunting', 20)
      
      this.saveState()
      return { success: true, message: `成功狩猎，获得 ${amount} 肉` }
    } else {
      // 失败可能受伤
      const damage = Math.floor(Math.random() * 10)
      this.state.hp = Math.max(0, this.state.hp - damage)
      
      this.saveState()
      return { success: false, message: `狩猎失败，受伤 -${damage}HP` }
    }
  }

  /**
   * 钓鱼
   */
  fish() {
    if (this.state.energy < 15) {
      return { success: false, message: '精力不足' }
    }
    
    this.state.energy -= 15
    
    const baseAmount = this.state.inventory.fishing_rod > 0 ? 4 : 2
    this.state.inventory.fish += baseAmount
    
    this.addSkillExp('gathering', 15)
    
    this.saveState()
    return { success: true, message: `钓到 ${baseAmount} 条鱼` }
  }

  /**
   * 制作物品
   */
  craftItem(itemId) {
    const recipes = this.getCraftingRecipes()
    const recipe = recipes[itemId]
    
    if (!recipe) {
      return { success: false, message: '未知配方' }
    }
    
    // 检查材料
    for (const [material, amount] of Object.entries(recipe.cost)) {
      if ((this.state.inventory[material] || 0) < amount) {
        return { success: false, message: `材料不足：缺少 ${this.getResourceName(material)}` }
      }
    }
    
    // 消耗材料
    for (const [material, amount] of Object.entries(recipe.cost)) {
      this.state.inventory[material] -= amount
    }
    
    // 制作成功率
    const baseRate = 0.8
    const skillBonus = this.state.skills.crafting.level * 0.02
    const successRate = Math.min(0.95, baseRate + skillBonus)
    
    if (Math.random() < successRate) {
      this.state.inventory[itemId] = (this.state.inventory[itemId] || 0) + 1
      this.addSkillExp('crafting', 25)
      
      this.saveState()
      return { success: true, message: `成功制作 ${recipe.name}` }
    } else {
      this.saveState()
      return { success: false, message: '制作失败，材料已消耗' }
    }
  }

  /**
   * 建造建筑
   */
  buildStructure(buildingId) {
    const buildings = this.getBuildingDefinitions()
    const building = buildings[buildingId]
    
    if (!building) {
      return { success: false, message: '未知建筑' }
    }
    
    if (this.state.buildings[buildingId]) {
      return { success: false, message: '已经建造过了' }
    }
    
    // 检查材料
    for (const [material, amount] of Object.entries(building.cost)) {
      if ((this.state.inventory[material] || 0) < amount) {
        return { success: false, message: `材料不足：缺少 ${this.getResourceName(material)}` }
      }
    }
    
    // 消耗材料
    for (const [material, amount] of Object.entries(building.cost)) {
      this.state.inventory[material] -= amount
    }
    
    this.state.buildings[buildingId] = true
    this.addSkillExp('crafting', 50)
    
    this.saveState()
    return { success: true, message: `成功建造 ${building.name}` }
  }

  /**
   * 休息恢复
   */
  rest() {
    const baseRestore = 30
    const shelterBonus = this.state.buildings.shelter ? 20 : 0
    const restore = baseRestore + shelterBonus
    
    this.state.energy = Math.min(100, this.state.energy + restore)
    this.state.sanity = Math.min(100, this.state.sanity + 10)
    
    // 消耗时间
    this.state.hunger = Math.max(0, this.state.hunger - 5)
    this.state.thirst = Math.max(0, this.state.thirst - 8)
    
    this.saveState()
    return { success: true, message: `休息恢复，精力 +${restore}` }
  }

  /**
   * 吃东西
   */
  eat(food) {
    if (!this.state.inventory[food] || this.state.inventory[food] <= 0) {
      return { success: false, message: '没有这个食物' }
    }
    
    this.state.inventory[food]--
    
    const foodEffects = {
      berry: { hunger: 5, hp: 2 },
      fish: { hunger: 15, hp: 5 },
      meat: { hunger: 20, hp: 10 },
      cooked_meat: { hunger: 40, hp: 20 },
      coconut: { hunger: 3, thirst: 5 }
    }
    
    const effect = foodEffects[food] || { hunger: 5 }
    
    if (effect.hunger) this.state.hunger = Math.min(100, this.state.hunger + effect.hunger)
    if (effect.hp) this.state.hp = Math.min(100, this.state.hp + effect.hp)
    if (effect.thirst) this.state.thirst = Math.min(100, this.state.thirst + effect.thirst)
    
    this.saveState()
    return { success: true, message: `食用 ${this.getResourceName(food)}`, effect }
  }

  /**
   * 喝水
   */
  drink(waterType = 'water') {
    if (!this.state.inventory[waterType] || this.state.inventory[waterType] <= 0) {
      return { success: false, message: '没有水' }
    }
    
    this.state.inventory[waterType]--
    this.state.thirst = Math.min(100, this.state.thirst + 20)
    
    this.saveState()
    return { success: true, message: '口渴度 +20' }
  }

  /**
   * 增加技能经验
   */
  addSkillExp(skill, exp) {
    if (!this.state.skills[skill]) return
    
    this.state.skills[skill].exp += exp
    
    // 升级检查（每级需要100经验）
    const requiredExp = (this.state.skills[skill].level + 1) * 100
    if (this.state.skills[skill].exp >= requiredExp && this.state.skills[skill].level < 10) {
      this.state.skills[skill].level++
      this.state.skills[skill].exp = 0
      return { levelUp: true, skill, level: this.state.skills[skill].level }
    }
    
    return null
  }

  /**
   * 获取位置资源
   */
  getLocationResources(location) {
    const locationResources = {
      beach: ['wood', 'coconut', 'fish'],
      forest: ['wood', 'berry', 'vine', 'medicine'],
      mountain: ['stone', 'map_fragment'],
      cave: ['stone', 'torch'],
      ruins: ['map_fragment'],
      harbor: ['wood', 'stone']
    }
    
    return locationResources[location] || ['wood']
  }

  /**
   * 获取制作配方
   */
  getCraftingRecipes() {
    return {
      axe: { name: '斧头', cost: { wood: 3, stone: 2 } },
      spear: { name: '矛', cost: { wood: 2, stone: 1 } },
      fishing_rod: { name: '鱼竿', cost: { wood: 2, vine: 3 } },
      torch: { name: '火把', cost: { wood: 1, vine: 1 } },
      rope: { name: '绳索', cost: { vine: 3 } },
      plank: { name: '木板', cost: { wood: 2 } }
    }
  }

  /**
   * 获取建筑定义
   */
  getBuildingDefinitions() {
    return {
      shelter: { name: '简易庇护所', cost: { wood: 10, vine: 5 } },
      campfire: { name: '篝火', cost: { wood: 5, stone: 3 } },
      water_collector: { name: '雨水收集器', cost: { wood: 8, vine: 10 } },
      storage: { name: '储藏室', cost: { wood: 15, stone: 10 } },
      workshop: { name: '工作台', cost: { wood: 20, stone: 15 } },
      boat: { name: '独木舟', cost: { plank: 30, rope: 20 } },
      signal_tower: { name: '信号塔', cost: { wood: 50, stone: 30 } }
    }
  }

  /**
   * 资源名称映射
   */
  getResourceName(resource) {
    const names = {
      berry: '浆果', fish: '鱼', meat: '肉', wood: '木材',
      stone: '石头', vine: '藤蔓', water: '水', coconut: '椰子',
      axe: '斧头', spear: '矛', fishing_rod: '鱼竿',
      medicine: '草药', torch: '火把', map_fragment: '地图碎片',
      rope: '绳索', plank: '木板', cooked_meat: '熟肉'
    }
    return names[resource] || resource
  }

  /**
   * 检查剧情事件
   */
  checkStoryEvents() {
    const events = {
      day_1: { scene: '你醒来时发现自己躺在沙滩上，周围是船只的残骸...', triggered: false },
      day_7: { scene: '你已经在这里生存了一周。远处似乎有烟雾升起...', unlocks: 'forest' },
      day_30: { scene: '你逐渐适应了岛上的生活。今晚做了一个奇怪的梦...', unlockNPC: 'mysterious_figure' },
      day_50: { scene: '你发现了一座废弃的港口...', unlocks: 'harbor' },
      day_100: { scene: '远处传来直升机的声音！', ending: 'rescued' }
    }
    
    const eventKey = `day_${this.state.day}`
    if (events[eventKey] && !this.state.triggeredEvents.includes(eventKey)) {
      this.state.triggeredEvents.push(eventKey)
      return events[eventKey]
    }
    
    return null
  }

  /**
   * 检查随机事件
   */
  checkRandomEvents() {
    if (Math.random() > 0.3) return null
    
    const events = ['storm', 'wildlife', 'treasure']
    const event = events[Math.floor(Math.random() * events.length)]
    
    return { type: event, day: this.state.day }
  }

  /**
   * 检查结局
   */
  checkEndings() {
    // 死亡结局
    if (this.state.hp <= 0) {
      return this.triggerEnding('death_injury')
    }
    
    if (this.state.hunger <= 0 && this.state.day > 3) {
      return this.triggerEnding('death_starvation')
    }
    
    if (this.state.sanity <= 0 && this.state.day >= 30) {
      return this.triggerEnding('madness')
    }
    
    // 胜利结局
    if (this.state.day >= 100 && this.state.hp > 0) {
      return this.triggerEnding('rescued')
    }
    
    if (this.state.buildings.boat && this.state.hp > 50) {
      return this.triggerEnding('escape_by_boat')
    }
    
    // 隐藏结局
    if (this.state.day >= 150 && 
        this.state.buildings.shelter && 
        this.state.buildings.workshop && 
        this.state.buildings.storage &&
        this.state.skills.survival.level >= 10) {
      return this.triggerEnding('island_master')
    }
    
    if (this.state.inventory.map_fragment >= 5 && 
        this.state.exploredLocations.ruins &&
        this.state.flags.mysterious_book_found) {
      return this.triggerEnding('civilization')
    }
    
    return null
  }

  /**
   * 触发结局
   */
  triggerEnding(endingId) {
    this.state.ending = endingId
    this.state.isGameOver = true
    this.saveState()
    return this.getEndingInfo(endingId)
  }

  /**
   * 获取结局信息
   */
  getEndingInfo(endingId) {
    const endings = {
      rescued: {
        id: 'ending_rescued',
        name: '🚁 成功获救',
        description: '你坚持了100天，终于等来了救援队',
        rank: 'B'
      },
      escape_by_boat: {
        id: 'ending_escape',
        name: '⛵ 独自离开',
        description: '你建造了船只，凭自己的力量离开了荒岛',
        rank: 'A'
      },
      island_master: {
        id: 'ending_master',
        name: '👑 岛屿之主',
        description: '你完全掌控了这座岛屿，选择留下成为岛主',
        rank: 'S'
      },
      civilization: {
        id: 'ending_civilization',
        name: '🏛️ 文明发现',
        description: '你发现了岛上的古代文明遗迹，解开了岛屿的秘密',
        rank: 'S+'
      },
      death_starvation: {
        id: 'ending_death_hunger',
        name: '💀 饥饿而死',
        description: '你未能找到足够的食物...',
        rank: 'F'
      },
      death_injury: {
        id: 'ending_death_hp',
        name: '💀 伤重不治',
        description: '你的伤势过重，最终倒下了...',
        rank: 'F'
      },
      madness: {
        id: 'ending_madness',
        name: '🌀 迷失心智',
        description: '孤独和绝望让你失去了理智...',
        rank: 'F'
      }
    }
    
    return endings[endingId] || null
  }

  /**
   * 保存游戏状态
   */
  saveState() {
    try {
      uni.setStorageSync('island_game_state', JSON.stringify(this.state))
    } catch (error) {
      console.error('保存游戏状态失败:', error)
    }
  }

  /**
   * 加载游戏状态
   */
  loadState() {
    try {
      const saved = uni.getStorageSync('island_game_state')
      if (saved) {
        this.state = JSON.parse(saved)
        this.applyDifficultyModifiers()
        return this.state
      }
    } catch (error) {
      console.error('加载游戏状态失败:', error)
    }
    return null
  }

  /**
   * 获取当前状态
   */
  getState() {
    return { ...this.state }
  }
}

// 导出单例
const gameManager = new IslandGameManager()
export default gameManager 